import env from "./env.js";
import {
	userToken
} from '@/network/api.js'

function service(options = {}) {
    options.url = `${env.baseUrl}${options.url}`;
    options.header = {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': `Bearer ${uni.getStorageSync("token")}`,
    };

    return new Promise((resolved, rejected) => {
        uni.request({
            ...options,
            success: (res) => {
                switch (res.data.err) {
                    case "-1":
                    case -1:
                        uni.showToast({
                            icon: "none",
                            duration: 3000,
                            title: `${res.data.msg}`
                        });
                        // resolved(res.data);
						uni.hideLoading()
                        return;
                    case -500:
                    case -501:
                    case -502:
                        userToken({
                            open_id: uni.getStorageSync("openid")
                        }).then(tokenRes => {
                            uni.setStorageSync("token", tokenRes.data.token);
                            const newOptions = {
                                ...options,
                                url: options.url.substring(options.url.lastIndexOf(".com") + 4),
                                header: {
                                    ...options.header,
                                    'Authorization': `Bearer ${tokenRes.data.token}`
                                }
                            };
                            return service(newOptions);
                        }).then(newRes => {
                            resolved(newRes);
                        }).catch(refreshError => {
                            rejected(refreshError);
                        });
                        return;
                    default:
                        resolved(res.data);
                }
            },
            fail: (err) => {
                uni.showToast({
                    icon: "none",
                    duration: 3000,
                    title: "服务器错误，请稍后再试"
                });
                rejected(err);
            }
        });
    });
}
export default service;